import router from "@/router/index";
import { useUserStore } from "@/stores/user";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from "@/util/token";
const Whitelist = ['/', '/login', '/error', '/404']
import type { RouteLocationNormalizedGeneric } from "vue-router";
import {useLayoutStore} from "@/stores/layout";
import * as path from "path";
/*watch(() => route.path, () => {
  let tab = {
    name: route.path,
    title: route.meta.title as string,
    isClosable: route.meta.isClosable
  } as tabType
  layoutStore.addTab(tab)
})*/
router.beforeEach((to: RouteLocationNormalizedGeneric, from, next) => {
    NProgress.start();
    const store = useUserStore()
    const hasetoken = getToken()
    //如果已经登录还在访问登录页，则跳转主页
    if (to.path == "/login" && hasetoken) {
        next('/')
    }
    if (Whitelist.indexOf(to.path) == -1) {
        // 如果已经登录，但是还没有获取路由，就获取权限数据
        if (store.routers.length == 0 && hasetoken) {
            store.getPermission().then(() => {
                router.addRoute(
                    {
                        path: '/layout',
                        name: 'layout',
                        meta: {
                            title: '首页',
                        },
                        component: () => import('@/layout/index.vue'),
                        redirect: '/layout/home',
                        children: store.routers
                    }
                )
                // 动态添加路由
                return next({ ...to, replace: true })
            }).catch((err) => {
                console.log("路由守卫报错了，请仔细检查是不是获取权限数据出现错误", err);
                return next('/login')
            })
        }
        else {
            NProgress.done()
            if (!hasetoken) {
                // 如果没有登录，则直接跳转登录页
                next('/login')
            }
            if (hasetoken && router.hasRoute(to.name as string)) {
                console.log("拥有权限访问受限制的路由");
                const isLayoutRoute = /^\/layout/.test(to.path);
                if (isLayoutRoute) {
                    const layoutStore = useLayoutStore()
                    let tab = {
                        name: to.path,
                        title: to.meta.title as string,
                        isClosable: to.meta.isClosable
                    }
                    layoutStore.addTab(tab)
                }
                next()
            } else {
                console.log("拥有的路由" + JSON.stringify(router.getRoutes()), "访问的路由", to.path, "是否具有权限访问路由？", router.hasRoute(to.name as string));
                // next('/404')
                next()
            }
        }
    } else {
        // 在白名单，放行
        NProgress.done()
        next()
    }
})
